<template>
  <div class="GoodsInfo">
        <div class="goods_left">
            <div class="goodsImg">
                <img :src="goodsList.goodsImg" alt="">
            </div>
            <div class="goodsCllect">
                <i class="fa fa-star"></i>
                <span>收藏商品</span>
            </div>
        </div>
        <div class="goods_right">
            <ul>
                <li>
                    <p> {{goodsList.goodsName}}</p>
                </li>
                <li>
                    <!-- <div class="flag" v-if="nowTime.getTime()<new Date(goodsList.startTime).getTime()"> -->
                    <div class="flag" v-if="compare1()">
                        <span class="gr">未开始</span>
                        <span class="gr_p">开始时间：{{goodsList.startTime}}</span>
                    </div>
                    <!-- <div class="flag" v-else-if="this.nowTimes.getTime()>new Date(this.goodsList.startTime).getTime()&&this.nowTimes.getTime()<new Date(this.goodsList.endTime).getTime()"> -->
                      <div class="flag" v-if="compare2()">
                        <span class="re">竞拍中</span>
                        <span class="re_p">倒计时:{{times}}</span>
                        <!-- <span ref="time"></span> -->
                    </div>
                    <!-- <div class="flag" v-else> -->
                      <div class="flag" v-if="compare3()">
                        <span class="gy">已结束--</span>
                        <span class="gy_p">该商品竞拍已经结束</span>
                    </div>
                </li>
                <li>
                    <p><span>商品编号:</span> {{goodsList.goodsId}}</p>
                    <hr>
                </li>
                <li>
                    <p><span>商品类名:</span> {{goodsList.goodsCategory}}</p>
                    <hr>
                </li>
                <li>
                    <p><span>底价/当前价:</span> {{goodsList.goodsPrice}}￥ /当前价{{goodsList.maxPrice}}￥</p>
                    <hr>
                </li>
                <li>
                    <p>
                        <el-button v-if="state != ''&&!compare3()" type="primary" @click="auction"><i class="fa fa-plus"></i> 我要出价</el-button>
                        <!-- <span ></span> -->
                        <el-button v-if="state == ''&&!compare3()&&!compare1()" type="primary" @click="openMoney">先交保证金:{{goodsList.goodsPrice}}￥</el-button>
                        <!-- <span v-if="state == ''">先交保证金:{{goodsList.goodsPrice}}￥</span> -->
                        <el-button v-if="compare3()" type="primary">已结束</el-button>
                        <el-button v-if="compare1()" type="primary">未开始</el-button>
                    </p>
                    <hr>
                </li>
            </ul>
        </div>
  </div>
</template>

<script>
import axios from 'axios'
import { mapState} from "vuex";
export default {
    name:'GoodsInfo',
    props:['goodsList'],
    data() {
        return {
            nowTime:'',//当前时间
            nowTimes:'',
            endTime:'',//结束时间
            times:'',//剩余时间
            timer:null,
            state:'',//是否支付保证金
            money:'',//用户余额
            timer1:'',
            goodsId:'',//商品id
            Nickname:'',//用户昵称
            userPhone:'',//用户手机号
            maxPrice:'',//当前商品最高价
            nowTimes:'',//当前时间
        }
    },
    created() {
        this.nowTime = new Date() 
        this.nowTimes = new Date()
        this.endTime = this.goodsList.endTime
        this.goodsId = this.goodsList.goodsId
        this.maxPrice = this.goodsList.maxPrice
        this.getAlluserlist()
        this.getUserMoney()
        this.getUserList()
        this.getTime()
    },
    mounted() {
        console.log("结束时间为",this.endTime)
        this.sendEndTimg()
        this.$store.dispatch("getCommodityList");
        // console.log("Jiegupp",)
    },
    beforeDestroy() {
        clearTimeout(this.timer1)
    },
    methods: {
        sendEndTimg(){
          this.$bus.$emit('getEndtime',this.endTime)
        },
        // 时间转换
        formatDateTime (date) {
          var date = new Date(date)
          var y = date.getFullYear();
          var m = date.getMonth() + 1;
          m = m < 10 ? ('0' + m) : m;
          var d = date.getDate();
          d = d < 10 ? ('0' + d) : d;
          // return y + '-' + m + '-' + d+' '+h+':'+minute;
          return y + '-' + m + '-' + d
        },
        getNowTimes(){
          this.nowTime = this.formatDateTime(new Date()) + ' ' + String(new Date()).slice(16,24)
          console.log("当前时间111",this.nowTime)
        },
        auction(){
          this.getNowTimes()
          this.$prompt('提示：输入的价格必须比上一次用户竞拍价高', '请输入你要竞拍的价格', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(({ value }) => {
            // value就是输入的值
            if(value>this.maxPrice){
                //添加用户竞拍数据 
                axios.get("http://localhost:8080/api/addAuction/addAuctionlist",{
                  params:{
                    userId:localStorage.getItem('Token'),
                    goodsId:this.goodsId,
                    Nickname:this.Nickname,
                    userPhone:this.userPhone,
                    price:value,
                    nowTime:this.nowTime
                  }
                }).then(
                  res=>{
                    this.$message({
                      message:'竞价成功',
                      type:'success'
                    })
                  },
                  error=>{
                    console.log("b",error.message)
                  }
                );
                // 更新商品竞拍最高价
                axios.get("http://localhost:8080/api/updateGoodsMaxP/updateGoodsMaxPlist",{
                  params:{
                    maxPrice:value,
                    goodsId:this.goodsId,
                  }
                }).then(
                  res=>{
                    this.$message({
                      message:'商品信息更新成功',
                      type:'success'
                    })
                  },
                  error=>{
                    console.log("b",error.message)
                  }
                );
                this.$message({
                  type: 'success',
                  message: '竞价成功'
                });
                console.log("输入的值为：",value)
            }else{
              this.$message({
                type: 'info',
                message: '你的出价太低'
              });  
            }
            
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消输入'
            });       
          });
        },
        // 获取用户信息
        getUserList(){
            axios.get("http://localhost:8080/api/userlist/getlist",{
              params:{
                userId:localStorage.getItem('Token')
              }
            }).then(
              res=>{
                let result = res.data[0]
                this.Nickname = result.Nickname
                this.userPhone = result.userPhone
                this.$bus.$emit("getName",result.userName)
                console.log("用户信息",result,this.Nickname,this.userPhone)
                console.log("获取结果",res)
              },
              error=>{
                console.log("b",error.message)
              }
            )
        },
        //添加押金扣除
        lessMoney(){
          axios.get("http://localhost:8080/api/addMoneyChange/addMoneyChangelist",{
            params:{
              userId:localStorage.getItem('Token'),
              moneychange:`已经参加商品竞拍${this.goodsList.goodsName},扣除押金${this.goodsList.goodsPrice}元`
            }
          }).then(
            res=>{
            },
            error=>{
              console.log("88",error.message)
            }
          )
        },
        //是否支付押金参与竞拍
        openMoney() {
          this.$confirm('是否支付保证金，参与竞拍', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if(this.money>this.goodsList.goodsPrice){
                this.money = this.money - this.goodsList.goodsPrice
                this.addUserEarn()
                this.updateUserMoney()
                this.lessMoney()
                this.$message({
                  type: 'success',
                  message: '支付成功，您可以参加竞拍'
                });
                // this.$router.go(0)
                // this.getTime()
            }else{
                this.$message({
                  type: 'info',
                  message: '您的账户余额不足，请充值之后在来'
                }); 
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
          });
        },
        getTime() {
            // let nextDate = new Date(this.endTime);
             if(this.endTime == undefined){
                this.endTime = this.goodsList.endTime
            }
            this.endTime = this.goodsList.endTime
            let nextDate = new Date(this.endTime);
            console.log("结束时间为1",this.endTime)
            let currDate,currTime,nextTime,allTime,allSecond,d,h,m,s;
            this.timer = setInterval(()=>{
                // time = this.$refs.time
                //获取当前时间
                currDate = new Date();

                //现在时间距离1970/07/01剩余总毫秒数
                currTime = currDate.getTime();
                //将来时间距离1970/07/01剩余总毫秒数
                nextTime = nextDate.getTime();
                //将来时间距离现在时间的总毫秒数
                allTime = nextTime - currTime;
                
                /*
                毫秒转换成天时分秒的公式
                1、总秒数/3600/24——天
                2、总秒数/3600%24——时
                3、总秒数/60%60——分
                4、总秒数%60——秒
                */
               //求出总秒数
               allSecond = Math.floor(allTime/1000);
                //console.log(allSecond);

               d = Math.floor(allSecond/3600/24);
               h = Math.floor(allSecond/3600%24);
               m = Math.floor(allSecond/60%60);
               s = Math.floor(allSecond%60);

               this.times = `${d}天${h}时${m}分${s}秒`
              if(allSecond<=0){
                clearInterval(this.timer)
              }
            },1000)
        },
        // 获取用户是否提交定金
        getAlluserlist(){
            axios.get("http://localhost:8080/api/getUserEarn/getUserEarnlist",{
              params:{
                userId:localStorage.getItem('Token'),
                goodsId:this.goodsId
              }
            }).then(
              res=>{
                this.state = res.data
                console.log("状态查询结果1：",res.data)
              },
              error=>{
                console.log("88",error.message)
              }
            )
        },
        // 获取用户余额
        getUserMoney(){
            axios.get("http://localhost:8080/api/getUserMoney/getUserMoneylist",{
              params:{
                userId:localStorage.getItem('Token'),
              }
            }).then(
              res=>{
                this.money = res.data[0].money
                console.log("状态查询结果2：",res.data)
              },
              error=>{
                console.log("88",error.message)
              }
            )
        },
        // 更新用户余额
        updateUserMoney(){
            axios.get("http://localhost:8080/api/updateUserMoney/updateUserMoneylist",{
              params:{
                userId:localStorage.getItem('Token'),
                money:this.money
              }
            }).then(
              res=>{
                this.money = res.data[0].money
                console.log("状态查询结果1：",res.data[0].money)
              },
              error=>{
                console.log("88",error.message)
              }
            )
        },
        // 添加用户支付押金状态
        addUserEarn(){
            axios.get("http://localhost:8080/api/addUserEarn/addUserEarnlist",{
                params:{
                  userId:localStorage.getItem('Token'),
                  goodsId:this.goodsId,
                  state:1,
                }
              }).then(
                res=>{
                  this.$message({
                      message:'您已成功支付押金',
                      type:'success'
                    })
                  // console.log("添加成功")
                },
                error=>{
                  console.log("b",error.message)
                }
              );
        },
        compare1(){
          return this.nowTimes.getTime()<new Date(this.goodsList.startTime).getTime()
        },
        compare2(){
          // console.log("时间数据",this.nowTimes.getTime(),this.goodsList.startTime,this.goodsList.id)
          // console.log("判断结果1",this.nowTimes.getTime()>new Date(this.goodsList.startTime).getTime()&&this.nowTimes.getTime()<new Date(this.goodsList.endTime).getTime())
          return this.nowTimes.getTime()>new Date(this.goodsList.startTime).getTime()&&this.nowTimes.getTime()<new Date(this.goodsList.endTime).getTime()
        },
        compare3(){
          return this.nowTimes.getTime()>new Date(this.goodsList.endTime).getTime()
        }
    },
    computed:{
        
    },
    watch:{
        goodsList:function(newData){
            this.goodsList = newData;
        }
    }
}
</script>

<style scoped>
    .GoodsInfo{
        width: 100%;
        height: 450px;
        padding: 20px;
    }
    .goods_left{
        width: 33%;
        height: 100%;
        padding: 15px 0;
        float: left;
    }
    .goodsImg{
        width: 80%;
        height: 80%;
        margin: 0 auto;
    }
    .goodsImg img{
        width: 100%;
        height: 100%;
    }
    .goodsCllect{
        width: 40%;
        height: 10%;
        line-height: 38px;
        text-align: center;
        background-color: skyblue;
        margin: 5px auto;
        border-radius: 5px;
        font-size: 18px;
        color: #fff;
        cursor: pointer;
    }
    .goodsCllect i{
        margin-right: 5px;
    }
    .goods_right{
        float: left;
        width: 66%;
        height: 100%;
        text-align: left;
        padding: 15px 0;
    }
    .goods_right ul{
        width: 100%;
        height: 100%;
    }
    .goods_right ul li{
        width: 100%;
        height: 40px;
        padding-left: 20px;
        line-height: 40px;
        margin-bottom: 5px;
    }
    .goods_right ul li:first-child{
        height: 80px;
        line-height: 80px;
        font-family: "楷体";
        font-size: 24px;
        color: #333;
        font-weight: bold;
    }
    .goods_right ul li span{
        font-weight:bolder;
    }
    .goods_right ul li:last-child{
        height: 60px;
        line-height: 60px;
        cursor: pointer;
        
    }
    .goods_right ul li:last-child span{
        float: left;
        width: 120px;
        height: 40px;
        text-align: center;
        line-height: 40px;
        font-weight: normal;
        font-size: 14px;
        background-color: skyblue;
        color: #fff;
        border-radius: 5px;
    }
    .goods_right ul li:nth-child(2){
        height: 80px;
        line-height: 80px;
    }
    /* ---- */
    .flag{
        width: 100%;
        height: 80px;
        /* background-color: red; */
        opacity: .8;
        padding-left: 10px;
        background-image: url("./img/bg.jpg");
    }
    .flag span{
        float: left;
        height: 100%;
        
    }
    .flag span:first-child{
        width: 20%;
        text-align: center;
        color: #fff;
    }
    .flag span:last-child{
        width: 80%;
        text-align: left;
        padding-left: 10px;
        color: #000;
        font-weight: normal;
    }
    .gr{
        background-color: green;
    }
    .gr_p{
        background-color: #d4d4d4;
    }
    .re{
        background-color: red;
    }
    .gy{
        background-color: gray;
    }
    .gy_p{
        background-color: #f7f7f7;
    }
</style>